package com.lance.core.launch;

import com.lance.core.launch.service.LaucherService;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.*;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author lancecong
 * @version 1.0
 * @ClassName LanceApplication
 * @DESCRIPTION 替换掉springApplication 加载一些自己的定制
 * @create 2019-06-28 18:56
 **/
public class LanceApplication {
    public static ConfigurableApplicationContext run(String appName,Class<?> primarySource,
                                                     String... args) {
        SpringApplicationBuilder builder = createAppBuilder(appName,primarySource);
        return builder.run(args);
    }

    private static SpringApplicationBuilder createAppBuilder(String appName, Class<?> primarySource,String ...args) {
        Assert.hasText(appName, "[appName]服务名不能为空");
        // 读取环境变量，使用spring boot的规则
        ConfigurableEnvironment environment = new StandardEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addFirst(new SimpleCommandLinePropertySource(args));
        // 获取配置的环境变量
        String[] activeProfiles = environment.getActiveProfiles();
        // 判断环境:dev、test、prod
        List<String> profiles = Arrays.asList(activeProfiles);
        // 预设的环境
        List<String> presetProfiles = new ArrayList<>(Arrays.asList("dev","test","pro"));
        // 交集
        presetProfiles.retainAll(profiles);
        // 当前使用
        List<String> activeProfileList = new ArrayList<>(profiles);
        SpringApplicationBuilder builder = new SpringApplicationBuilder(primarySource);
        String profile;
        if (activeProfileList.isEmpty()) {
            // 默认dev开发
            profile ="dev";
            activeProfileList.add(profile);
            builder.profiles(profile);
        } else if (activeProfileList.size() == 1) {
            profile = activeProfileList.get(0);
        } else {
            // 同时存在dev、test、prod环境时
            throw new RuntimeException("同时存在环境变量:[" + StringUtils.arrayToCommaDelimitedString(activeProfiles) + "]");
        }


        ServiceLoader<LaucherService> loader = ServiceLoader.load(LaucherService.class);
        loader.forEach(laucherService ->  laucherService.laucher(builder, appName, profile));

        return  builder;
    }
}
